﻿#include "CThreadBase.h"

CThreadBase::CThreadBase(QObject *parent)
	: QThread(parent)
{
	m_bThreadStart = false;
	m_bThreadStop = false;
	
}
CThreadBase::CThreadBase()
{
	m_bThreadStart = false;
	m_bThreadStop = false;
	m_nNumber = 0;
}

CThreadBase::~CThreadBase()
{
	ThreadStop();
}

void CThreadBase::ThreadBegin()
{
	m_nNumber = 0;
	m_bThreadStart = true;
	m_bThreadStop = false;
	start();
}


void CThreadBase::ThreadStop()
{
	m_bThreadStart = false;
	while (isRunning())
	{
		msleep(10);
		//如果1000ms没有结束线程 强杀线程
		if (m_nNumber >= 100)
		{
			quit();
			m_bThreadStop = true;
		}
		else
		{
			m_nNumber++;
		}
	}
}

void CThreadBase::ThreadPause()
{

}

void CThreadBase::initEvent(int nNum)
{
	m_pSysMutex = new QMutex();
	m_pWaitCondition = new QWaitCondition();
	for (int i = 0; i < nNum; i++)
	{
		m_vecEvent.push_back(false);
	}
}

void CThreadBase::resetEvent(int nIndex)
{
	if (nIndex == -1 || nIndex >= m_vecEvent.size())
	{
		for (int i = 0; i < m_vecEvent.size(); i++)
		{
			m_vecEvent[i] = false;
		}
	}
	else
	{
		m_vecEvent[nIndex] = false;
	}
}

bool CThreadBase::setEvent(int nIndex)
{
	if (nIndex == -1 || nIndex >= m_vecEvent.size())
	{
		return false;
	}
	m_vecEvent[nIndex] = true;
	m_pWaitCondition->wakeAll();
	return false;
}

int CThreadBase::waitForObjects(int nTime)
{
	if (m_pSysMutex == nullptr || m_pWaitCondition == nullptr)
		return -1;
	//先判断队列里面有没有需要执行的事件
	for (int i = 0; i < m_vecEvent.size(); i++)
	{
		if (m_vecEvent[i] == true)
		{
			return i;
		}
	}
	//执行等待判断
	m_pSysMutex->lock();
	m_pWaitCondition->wait(m_pSysMutex, nTime);
	m_pSysMutex->unlock();
	//判断需要响应的事件
	for (int i = 0; i < m_vecEvent.size(); i++)
	{
		if (m_vecEvent[i] == true)
		{
			return i;
		}
	}
	return -1;
}


void CThreadBase::run()
{
	while (m_bThreadStart)
	{
		_workRun();
		msleep(10);
	}
	m_bThreadStop = true;
}

